package handler

import (
	"blockchain_data/config"
	"blockchain_data/handler/model"
	"blockchain_data/handler/okex"
	"blockchain_data/middleware"
	"blockchain_data/utils/errmsg"
	"fmt"
	"github.com/go-redis/redis"
	"github.com/robfig/cron/v3"
	"github.com/sirupsen/logrus"
	"strings"
	"time"
)
var redisSub *redis.Client
var log *logrus.Logger

func init()  {
	//redis的数据库
	redisSub = middleware.GetRedisPool(config.RedisHost,config.RedisPassWord,1)
	log = middleware.DataLogger()
}

func InitStart()  {

	bourse_list := strings.Split(config.Bourses,",")
	for _,bourse := range bourse_list{
		if bourse == "okex" {
			okexTick()
			okexFundingRate()
		}
	}
}

//每8小时获取一次okex资金费率
func okexFundingRate()  {
	c := cron.New()
	c.AddFunc(config.OkexTimedFundingRate, func() {
		//获取数据
		goods_list := strings.Split(config.OkexGoodsList,",")
		for _,goods := range  goods_list {
			//查询redis数据库
			key := fmt.Sprintf("okex_%s_%s_contract_code",goods,"fundingrate")
			contractCode_list := redisSub.LRange(key,0,-1).Val()
			for _, contractCode := range contractCode_list {
				okFundingSave := okex.FundingRateInit(goods,contractCode,"okex","tick",8)
				okFundingSave.GetFunding()
			}

		}
	})
	c.Start()
}
func okexTick()  {

	goods_list := strings.Split(config.OkexGoodsList,",")

	for _,goods := range goods_list{
		//服务列表
		key := fmt.Sprintf("okex_%s_%s_contract_code",goods,"tick")
		contractCode_list := redisSub.LRange(key,0,-1).Val()
		for _, contract_code := range contractCode_list {
			ticker := time.NewTicker(30 *time.Second)
			defer ticker.Stop()
			ch := make( chan model.Msg)
			save := okex.TickInit(goods,contract_code,"okex","tick")
			save.SubTrade(ch)
			select {
			case <-ticker.C:
				log.Error("订阅超时",contract_code)
			case msg := <-ch:
				if msg.Event == "error"{
					log.Errorf("订阅失败",contract_code)
				}else {
					log.Info("订阅成功",contract_code)
				}
			}
		}
	}
}

//添加订阅合约
func AddSub(bourse string,goods string,server string,contract_code string) int {
	var key string
	switch bourse {
	case "okex":
		switch goods {
		case "bswap":
			contract_code = fmt.Sprintf("%s-USD-SWAP",contract_code)
		case "uswap":
			contract_code = fmt.Sprintf("%s-USDT-SWAP",contract_code)
		}
		key = fmt.Sprintf("%s_%s_%s_contract_code",bourse,goods,server)
	default:
		log.Error("添加合约错误,没有对应的交易所")
		return errmsg.ERROR_SUB_BOURSE
	}
	//删除数据库里原来的合约
	delete_len := redisSub.LRem(key,3,contract_code).Val()
	//如果数据库有数据就关闭原有订阅
	if delete_len != 0{
		switch bourse {
		case "okex":
			save_val, _ := okex.WsTradeMap.Load(goods+server+contract_code)
			if save_val != nil {
				save := save_val.(*okex.OkTickSave)
				save.UnSubTrade()
			}
		}
	}

	//订阅合约
	err := redisSub.RPush(key,contract_code).Err()
	ch := make( chan model.Msg)


	if err != nil{
		log.Errorf("redis添加合约错误,err:%s",err)
		return errmsg.ERROR_SUB_REDIS
	}else {
		switch bourse {
		case "okex":
			switch server {
			case "tick":
				ticker := time.NewTicker(30 *time.Second)
				defer ticker.Stop()
				save := okex.TickInit(goods,contract_code,bourse,server)
				save.SubTrade(ch)
				select {
				case <-ticker.C:
					return errmsg.ERROR_WS_TIMEOUT
				case msg := <-ch:
					if msg.Event == "error"{
						return errmsg.ERROR_WS_ERROR
					}else {
						return errmsg.SUCCESS
					}
				}
			case "fundingrate":
				okFundingSave := okex.FundingRateInit(goods,contract_code,"okex","tick",8)
				code := okFundingSave.GetFunding()
				return code
			default:
				return errmsg.ERROR
			}
		default:
			return errmsg.ERROR
		}
	}
}

//删除订单合约
func DelSub(bourse string,goods string,server string,contract_code string) int {
	var key string
	switch bourse {
	case "okex":
		switch goods {
		case "bswap":
			contract_code = fmt.Sprintf("%s-USD-SWAP",contract_code)
		case "uswap":
			contract_code = fmt.Sprintf("%s-USDT-SWAP",contract_code)
		}
		key = fmt.Sprintf("%s_%s_%s_contract_code",bourse,goods,server)
	default:
		log.Error("删除合约错误,没有对应的交易所")
		return errmsg.ERROR_SUB_BOURSE
	}
	log.Infof("关闭合约：%s的%s服务",contract_code,server)
	//删除数据库里原来的合约
	err := redisSub.LRem(key,3,contract_code).Err()
	if err != nil{
		log.Errorf("redis删除合约错误,err:%s",err)
		return errmsg.ERROR_SUB_REDIS
	}else {
		var code = 200
		switch bourse {
		case "okex":
			save_val, _ := okex.WsTradeMap.Load(goods+server+contract_code)
			fmt.Println(save_val)
			if save_val != nil {
				save := save_val.(*okex.OkTickSave)
				save.UnSubTrade()
			}else {
				log.Errorf("删除订单合约,数据为空！！！")
			}
		}
		log.Infof("删除合约%s的服务%s",contract_code,server)
		return code
	}
}

//查询订单合约
func FindSub(bourse string,goods string, server string) ([]string,int) {
	var contractCode_list []string
	var key string
	switch bourse {
	case "okex":
		key = fmt.Sprintf("%s_%s_%s_contract_code",bourse,goods,server)
	default:
		log.Error("查询合约错误,没有对应的交易所")
		return contractCode_list,errmsg.ERROR_SUB_BOURSE
	}
	contractCode_list = redisSub.LRange(key,0,-1).Val()
	return contractCode_list,errmsg.SUCCESS
}